export const addUserInfo = async(req,res)=>{
    const { name, age, sex, birthDate, address } = req.body
    if(!name) return res.fail('姓名不能为空')
    if(!age) return res.fail('年龄不能为空')
    if(!sex) return res.fail('性别不能为空')
    if(!birthDate) return res.fail('出生不能为空')
    if(!address) return res.fail('地址不能为空')
    try{
        const userInfo = { name,
             age, 
             sex: sex === 0? '男' : '女',
             birthDate, 
             address
            }
        await req.db.userInfo.create ({
            data: userInfo,
        })
        res.send({success: true, message: '添加成功'})
    }catch(e){
        res.fail({success:false , message: '添加失败'})
    }
}

export const findUserInfo = async(req,res)=>{
    let { limit=20, page=1, a} = req.body
    limit = Number(limit)
    page = Number(page)
    try{
        const where = {}
        if(a) where.a = { startsWith: a }
        const result = await req.db.userInfo.findMany ({
            where,
            skip: (page-1)*limit,
            take: limit
        })
        const total = await req.db.userInfo.count({
            where
        })
        res.success({
            data: result,
            info: total
        })
    }catch(e){
        console.log(e)
        res.fail({success:false , message: '查询失败'})
    }
}

export const delUserInfo = async(req,res) =>{
    const { id } = req.body
    if(!id) return res.fail('id不能为空')
    try{
        await req.db.userInfo.delete({
            where:{
                id:Number(id)
            }
        })
        res.send({success:true, message:'删除成功'})
    }catch(e){
        console.log(e)
        res.fail('删除失败')
    }
}

export const updateUserInfo = async(req,res)=>{
    const { name, age, sex, birthDate, address, id } = req.body
    if(!id) return res.fail('id不能为空')
    try{
        const box = {}
        if(name) box.name = name
        if(age) box.age = age
        if(sex) box.sex = sex
        if(birthDate) box.birthDate = birthDate
        if(birthDate) box.address = address
        await req.db.userInfo.update({
            data: box,
            where:{
                id:Number(id)
            }
        })
        res.send({success: true, message: '更新成功'})
    }catch(e){
        console.log(e)
        res.fail({success: false, message: '更新失败'})
    }
}
//输入框查询
export const Search = async(req,res)=>{
    const { name } = req.body
    if(!name) return res.fail('查询名字不能为空')
    try{
        const username = await req.db.userInfo.findMany({
            where:{
                name
            }
        })
        res.send({success:true,info:username})
    }catch(e){
        console.log(e)
        res.fail({success: false ,message: '查询失败'})
    }
}